/*
 * Copyright (C), 2014-2016, org.esaydev
 * FileName: WechatRequest.java
 * Author:   jian
 * Date:     2016年3月18日 下午2:20:54
 */
package org.easydev.wechat.client.handle;

import org.easydev.wechat.client.dto.base.BaseParam;
import org.easydev.wechat.client.result.base.BaseWechatResult;
import org.easydev.wechat.client.util.WechatReqConfig;
import org.easydev.wechat.common.constants.WechatErrorCode;
import org.easydev.wechat.common.exception.WechatException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONObject;

/**
 * <Description> 默认处理类 <br>
 * 
 * @author jian<br>
 */
public abstract class WechatRequestHandle {

    /**
     * static LOGGER
     */
    protected static Logger LOGGER = LoggerFactory.getLogger(WechatRequestHandle.class);

    /**
     * Description: 处理微信请求<br>
     * 
     * @param parsms <br>
     * @param config <br>
     * @return <br>
     * @throws WechatException <br>
     */
    public BaseWechatResult doRequest(BaseParam parsms, WechatReqConfig config) {
        BaseWechatResult result = new BaseWechatResult();
        JSONObject resObj = null;
        try {
            resObj = dohandle(parsms, config);
            if (resObj.containsKey("errcode") && !"0".equals(resObj.getString("errcode"))) {
                result.setErrorCode(resObj.getString("errcode"));
                result.setErrorMsg(resObj.getString("errmsg"));
                return result;
            }
        } catch (WechatException e) {
            result.setErrorCode(e);
            LOGGER.error("[dohandle WechatException]", e);
        } catch (Exception e) {
            LOGGER.error("[dohandle Exception]", e);
        }
        if (null != resObj) {
            result.setData(resObj);
            result.setErrorCode(WechatErrorCode.REQUEST_SUCCESS);
        }
        return result;
    }

    /**
     * 处理去微信的请求 <br>
     * 
     * @param parsms 请求入参，包含token等信息<br>
     * @param config 请求配置，包含http信息<br>
     * @return 微信返回结果<br>
     * @throws WechatException 可能抛出的微信业务异常，需要自己处理<br>
     */
    protected abstract JSONObject dohandle(BaseParam parsms, WechatReqConfig config) throws WechatException;

    /**
     * Description: json转querystring参数调用微信<br>
     * 
     * @param json
     * @return <br>
     */
    protected static String castJsonToQueryString(JSONObject json) {
        StringBuilder params = new StringBuilder();
        if (null != json && !json.isEmpty()) {
            for (String key : json.keySet()) {
                params.append("&").append(key).append("=").append(json.get(key));
            }
        }
        return params.toString();
    }
}
